<template>
  <div class="pay-list" :class="payListStyle">
    <div class="pay-radio-list">
      <label class="pay-radio paypal">
        <span class="pay-label">
          <svg-icon icon-class="logoPaypal"></svg-icon>
          PayPal
        </span>
        <input
          class="radio"
          type="radio"
          v-model="payMode"
          value="5"
          name="payMode"
        />
      </label>
      <!-- <label class="pay-radio Googlepay">
        <span class="pay-label">
          <svg-icon icon-class="logoGooglepay"></svg-icon>
          Googlepay
        </span>
        <input
          class="radio"
          disabled
          type="radio"
          v-model="payMode"
          value="6"
          name="payMode"
        />
      </label> -->
    </div>
    <ul class="pay-active-list">
      <li
        @click="payMode = item.value"
        v-for="item of payModeList"
        :key="item.value"
        :class="{ active: payMode === item.value }"
      >
        <svg-icon :icon-class="item.icon"></svg-icon>
        <span class="pay-desc" v-text="item.text"></span>
      </li>
    </ul>
    <div
      class="payNow-box"
      :payNow-content="
        currentCard.rechargeId
          ? `Total ${currentCard.conversionCoin + currentCard.giveCoin} = ${
              currentCard.conversionCoin
            }Coins${
              currentCard.giveCoin ? ' + ' + currentCard.giveCoin + 'Coins' : ''
            }`
          : `Open members' free reading in the whole station`
      "
    >
      <mt-button
        id="paypal-button"
        class="pay-now"
        v-text="
          'Pay Now $' + (currentCard.rechargeSum || currentCard.price || 0)
        "
        @click="createOrder(currentCard)"
      ></mt-button>
      <!-- <PayPal
        :amount="
          currentCard.rechargeSum
            ? currentCard.rechargeSum + ''
            : currentCard.price + ''
        "
        currency="USD"
        :client="credentials"
        env="sandbox"
        :button-style="buttonStyle"
        @payment-authorized="paymentAuthorized"
        @payment-completed="paymentCompleted"
        @payment-cancelled="paymentCancelled"
      >
      </PayPal> -->
    </div>
    <div class="popup-box" v-show="isRechargeBox">
      <div class="paypal-box">
        <span class="close-icon" @click="isRechargeBox = false">
          <svg-icon icon-class="loginCloseIcon"></svg-icon>
        </span>
        <div id="recharge-box" v-if="isRechargeBox"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import { loadScript } from "@paypal/paypal-js";
import { Toast } from "mint-ui";
// import PayPal from "vue-paypal-checkout";
export default {
  props: {
    payListStyle: {
      type: String,
      default: "myAccount-pay-list",
    },
    currentCard: {
      type: Object,
    },
  },
  data() {
    return {
      payMode: 5, //支付方式
      payModeList: [
        {
          icon: "logoPaypal",
          value: 5,
          text: "PayPal",
        },
        // {
        //   icon: "logoGooglepay",
        //   value: 6,
        //   text: "Googlepay",
        // },
      ],
      // credentials: {
      //   //填写沙箱环境client_id
      //   sandbox:
      //     "AdYXcJST_chgfAHaz4gozY-oK2MoO8QryXqSerdBOq7AU254HC9GL_EDccAhmo7sbjzoEetP6IJlSP9L",
      //   // 填写线上环境client_id
      //   production:
      //     "AdYXcJST_chgfAHaz4gozY-oK2MoO8QryXqSerdBOq7AU254HC9GL_EDccAhmo7sbjzoEetP6IJlSP9L",
      // },
      // //付款按钮样式
      // buttonStyle: {
      //   label: "pay", //checkout
      //   size: "responsive",
      //   shape: "rect",
      //   color: "gold", // gold | blue | silver | black
      // },
      clientId:
        process.env.VUE_APP_MODE === "production"
          ? "AfJ-F6EHxaNS02dMlda-vQw2zBqdPEUNpjBtCFJf-wQDJsltaorA0KTio73ccPbM9cT22iB8ZGnJNooh"
          : "AeEX1PNMNaP3RuV8JTBMznAhs_gOfFwloG6SG3TiQh1_MBj0YZHlWYPKvdjH1q5GrpPSApZka-bOmhF2",
      outOrderNo: "", //三方订单号
      orderNo: "", // 本站订单号
      isRechargeBox: false,
    };
  },
  components: {
    // PayPal,
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    ...mapMutations({
      setShowPopup: "SET_SHOW_POPUP",
      setCurrentPopup: "SET_CURRENT_POPUP",
    }),
    // paypal支付
    // paymentAuthorized(data) {
    //   // 授权完成的回调，可以拿到订单id
    //   console.log("授权完成");
    //   console.log(data);
    //   this.orderId = data.orderID;
    //   this.createOrder();
    // },
    // paymentCompleted(data) {
    //   // 用户支付完成的回调，可以拿到订单id
    //   console.log("用户支付完成");
    //   console.log(data);
    //   this.payPalNotify(this.orderId);
    // },
    // paymentCancelled(data) {
    //   // 用户取消交易的回调
    //   console.log("用户取消交易");
    //   console.log(data);
    // },

    // 创建订单
    async createOrder(item) {
      if (this.userInfo) {
        let params = {
          bookId: "", //看过后充值的书籍id
          gainUserId: this.userInfo ? this.userInfo.authorId : "", //被充值用户ID
          orderType: item.rechargeId ? 1 : item.vipId ? 3 : null, //1 书币充值 ; 2 plus会员充值；3 premium会员充值
          payType: this.payMode, //支付方式 1 微信； 2 支付宝；3 QQ钱包 4 苹果支付 5 PayPal支付 6 google内购
          rechargeId: item.rechargeId, //书币充值套餐ID
          vipId: item.vipId, //会员套餐Id
        };
        let res = await this.$api.home.createOrder(params);
        if (res.code === 1) {
          // window.open(res.source.outOrderNo);
          let orderNo = res.source.orderId;
          let token = res.source.Id;
          let that = this;
          this.isRechargeBox = true;
          loadScript({
            "client-id": this.clientId,
          })
            .then((paypal) => {
              paypal
                .Buttons({
                  createOrder: function (data, actions) {
                    // This function sets up the details of the transaction, including the amount and line item details.
                    return token;
                  },
                  onApprove: function (data, actions) {
                    return actions.order.capture().then(function (details) {
                      // 支付完成的回调.
                      that.isRechargeBox = false;
                      // alert(
                      //   "Transaction completed by " +
                      //     details.payer.name.given_name
                      // );
                      // Call your server to save the transaction
                      // fbq("track", "Purchase", {
                      //   currency: "USD",
                      //   value: 30.0,
                      // });
                      that.payPalNotify(orderNo, details.id);
                      return "";
                    });
                  },
                  onCancel: function () {
                    that.isRechargeBox = false;
                    Toast("Payment Canceled");
                  },
                  onError: function () {
                    that.isRechargeBox = false;
                    Toast("Payment Failded");
                  },
                })
                .render("#recharge-box")
                .catch((error) => {
                  console.error("failed to render the PayPal Buttons", error);
                });
            })
            .catch((error) => {
              console.error("failed to load the PayPal JS SDK script", error);
            });
        }
      } else {
        this.setCurrentPopup({ currentPopup: "loginReminder" });
        this.setShowPopup(true);
      }
    },
    // 贝宝支付二次验证
    async payPalNotify(orderNo, outOrderNo) {
      let params = {
        orderNo, //本站订单号
        orderType: this.currentCard.rechargeId
          ? 1
          : this.currentCard.vipId
          ? 3
          : null, //1 书币充值 ; 2 plus会员充值；3 premium会员充值
        outOrderNo, //paypal订单号
        // userId: this.userInfo.authorId, //用户id
      };
      let res = await this.$api.home.payPalNotify(params);
      // console.log(res);
      if (res.code === 1) {
        Toast("Payment Successful");
        this.$emit("recharge", res.source);
      } else {
        Toast("Payment Failded");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.pay-list {
  margin-top: 54px;
  &.myAccount-pay-list {
    .pay-radio-list {
      .pay-radio {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        &.Googlepay {
          margin-top: 48px;
          // 禁用googlepay
          .pay-label {
            opacity: 0.3;
          }
        }
        .pay-label {
          display: flex;
          align-items: center;
          font-size: 32px;
          color: #333333;
          font-weight: 500;
          .svg-icon {
            width: 67px;
            height: 67px;
            margin-right: 16px;
          }
        }
        .radio {
          width: 46px;
          height: 46px;
        }
      }
    }
    .pay-active-list {
      display: none;
    }
  }
  &.reader-pay-list {
    .pay-radio-list {
      display: none;
    }
    .pay-active-list {
      display: flex;
      li {
        width: 218px;
        height: 160px;
        box-sizing: border-box;
        margin-left: 32px;
        border-radius: 16px;
        border: 2px solid #eeeeee;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: space-between;
        &.active {
          border-color: #e86472;
          span.pay-desc {
            color: #e86472;
            background: #fae0e3;
          }
        }
        .svg-icon {
          width: 67px;
          height: 67px;
          margin-top: 22px;
        }
        span.pay-desc {
          width: 100%;
          height: 56px;
          font-size: 32px;
          line-height: 56px;
          color: #999999;
          font-weight: 500;
          text-align: center;
          background: #eeeeee;
          border-radius: 0px 0px 14px 14px;
        }
      }
    }
    .payNow-box {
      &::before {
        content: attr(payNow-content);
        width: 100%;
        height: 46px;
        font-size: 22px;
        line-height: 46px;
        text-align: center;
        font-weight: 500;
        display: block;
        color: #e86472;
        background: rgba(232, 100, 114, 0.1);
      }
    }
  }
  > .payNow-box {
    // width: 100%;
    // height: 108px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 998;
    > .pay-now {
      width: 100%;
      height: 108px;
      color: #ffffff;
      font-size: 34px;
      font-weight: 600;
      background: linear-gradient(270deg, #e25178 0%, #f16d56 100%);
    }
  }
  > .popup-box {
    width: 100%;
    height: 100%;
    z-index: 999;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    .paypal-box {
      width: 660px;
      height: 460px;
      background: #fff;
      border-radius: 24px;
      position: relative;
      .close-icon {
        .svg-icon {
          width: 48px;
          height: 48px;
          position: absolute;
          top: 0;
          right: 0;
        }
      }
      #recharge-box {
        width: 100%;
        height: 100%;
        padding: 0 30px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
